<?php

namespace Modules\Customer\Http\Controllers;

use App\Http\Controllers\Controller;
use Catch\Exceptions\FailedException;
use Illuminate\Http\Request;
use Modules\Customer\Models\Customer;

class AuthController extends Controller
{
    /**
     * 登录
     * @param Request $request
     * @return array
     * @throws FailedException
     */
    public function login(Request $request)
    {
        $uniqueId = $request->get('unique_id');
        $customer = Customer::query()->where('unique_id', $uniqueId)->first();

        if (empty($customer)) {
            throw new FailedException('用户不存在，请先授权');
        }

        if ($customer['status'] == 0) {
            throw new FailedException('用户账号异常，无法登录');
        }

        return ['token' => $customer['uniqueId'] , 'username' => $customer['username']];
    }


    /**
     * 注册
     * @param Request $request
     * @return array
     * @throws FailedException
     */
    public function register(Request $request)
    {
        $phone = $request->get('phone');
        $uniqueId = $request->get('unique_id');

        $customer = Customer::query()->where('phone', $phone)->first();
        if (empty($customer)) {
            throw new FailedException('用户尚未开通账户，无法登录');
        }

        if ($customer['status'] == 0) {
            throw new FailedException('用户账号异常，无法登录');
        }

        $data['unique_id'] = $uniqueId;

        Customer::query()->insert($data);

        return ['token' => $uniqueId , 'username' => $customer['username']];
    }
}
